#include "graphics.h"
#include "textures.h"
#include "map.h"

int running = 0;
int textureDim = 64;
map_t map;

void updateMapAt(int x, int y, int clear)
{
  int t = map.map[x + y * map.mapCols];
  map.map[x + y * map.mapCols] = (clear) ? 0 : (t) % 9 + 1;
}

int processInput()
{
  int mouseX, mouseY;
  Uint32 mouseButtonMap;
  SDL_Event event;
  SDL_PollEvent(&event);
  switch (event.type)
  {
  case SDL_WINDOWEVENT:
    return 1;
  case SDL_QUIT:
    running = 0;
    break;
  case SDL_MOUSEBUTTONDOWN:
    mouseButtonMap = SDL_GetMouseState(&mouseX, &mouseY);
    if (mapScreenToMapCoord(&mouseX, &mouseY) > 0)
    {
      updateMapAt(mouseX, mouseY, mouseButtonMap & SDL_BUTTON(SDL_BUTTON_RIGHT));
      return 1;
    }
    break;
  case SDL_KEYDOWN:
    switch (event.key.keysym.sym)
    {
    case SDLK_F3:
      saveMap(map, "level.map");
      break;
    case SDLK_ESCAPE:
      running = 0;
      break;
    default:
      break;
    }
    break;
  }
  return 0;
}

void renderMap(int width, int height, int *mapData)
{
  int x = 0, y = 0, i = 0, j = 0, t = 0;

  clearColourBuffer(0);

  // TODO: replace with SDL_Image or mmap
  // or at something more efficient..

  for (x = 0; x < width; x++)
    for (y = 0; y < height; y++)
    {
      t = mapData[x + y * width];
      if (t > 0 && t < 9)
      {
        for (i = 0; i < textureDim; i++)
          for (j = 0; j < textureDim; j++)
            drawPixel(i + (textureDim * x), j + (textureDim * y), wallTextures[t - 1].texture_buffer[i + j * textureDim]);
      }
    }

  renderColourBuffer();
}

int main(int argc, char **argv)
{
  loadWallTextures();
  map = loadMap("level.map");
  running = initialiseWindow(textureDim, map.mapCols, map.mapRows);
  while (running)
  {
    if (processInput())
      renderMap(map.mapCols, map.mapRows, map.map);
    SDL_Delay(10);
  }
  SDL_Quit();
  return 0;
}
